package eclipse.client.threadpool;
import eclipse.*;
import eclipse.client.Database;
import eclipse.lib.sockets.*;
import eclipse.util.*;
public class MainLoopThread extends ThreadedTimer 
{	
	private int skip = 0;
	private int latency = 30;
	public MainLoopThread(LATENCY lag)
	{
		System.out.println(lag);
		if(lag == LATENCY.LOW)
			latency = 23;
		else if(lag == LATENCY.MEDIUM)
			latency = 15;
		else if(lag == LATENCY.HIGH)
			latency = 10;
		else if(lag == LATENCY.EXTRAHIGH)
			latency = 5;
		setEnabled(true);		
		setInterval(1000/latency);
		setName("Main Loop Thread");
		start();		
	}
	public void tick()
	{
		if(Database.player == null)
			return;
		checkMovement();				
		animate();
	}	
	public void animate()
	{		
		if(!Database.player[Database.myID].character.cMoving)
			return;
		skip++;
		if((skip % 4 == 0))			
		{
			int frame = Database.player[Database.myID].character.cFrame;
			if(frame < 3)
				frame++;
			else
				frame = 0;
			Database.player[Database.myID].character.cFrame = frame;
		}		
		ClientDataHandle.sendCharPosition();
		//TODO: send data to server
	}
	public void checkMovement()
	{
		if(Database.glInterface == null)
			return;
		if(Database.player == null)
			return;
		if(Database.player[Database.myID] == null)
			return;
		float moveVal = 2f;
		moveVal = (30f/latency) * moveVal;
		if(Database.glInterface.getLeft())			
		{
			Database.player[Database.myID].character.cPos.x =
				Database.player[Database.myID].character.cPos.x - moveVal;
			Database.player[Database.myID].character.cDir = Constants.DIR_LEFT;
			Database.player[Database.myID].character.cMoving = true;
		}
		else if(Database.glInterface.getRight())
		{
			Database.player[Database.myID].character.cPos.x =
				Database.player[Database.myID].character.cPos.x + moveVal;
			Database.player[Database.myID].character.cDir = Constants.DIR_RIGHT;
			Database.player[Database.myID].character.cMoving = true;
		}
		else if(Database.glInterface.getUp())
		{
			Database.player[Database.myID].character.cPos.y =
				Database.player[Database.myID].character.cPos.y - moveVal;
			Database.player[Database.myID].character.cDir = Constants.DIR_UP;
			Database.player[Database.myID].character.cMoving = true;
		}
		else if(Database.glInterface.getDown())
		{
			Database.player[Database.myID].character.cPos.y =
				Database.player[Database.myID].character.cPos.y + moveVal;
			Database.player[Database.myID].character.cDir = Constants.DIR_DOWN;
			Database.player[Database.myID].character.cMoving = true;
		}
		else
		{
			if(Database.player[Database.myID].character.cMoving)
			{
				Database.player[Database.myID].character.cMoving = false;
				Database.player[Database.myID].character.cFrame = 0;
				ClientDataHandle.sendCharPosition();
			}
		}
	}
}
